package com.campus.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.commons.entity.DeScore;
import com.campus.app.mapper.DeScoreMapper;
import com.campus.app.service.DeScoresService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.commons.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 学部积分表 服务实现类
 * </p>
 *
 * @author Rin
 * @since 2021-02-01
 */
@Service
public class DeScoreServiceImpl extends ServiceImpl<DeScoreMapper, DeScore> implements DeScoresService {
@Autowired
private DeScoreMapper deScoreMapper;
    @Override
    public boolean addDeInfo() {
        // 获取Id 和他们 的de id
        List<DeScore> deStudent = deScoreMapper.getDeStudents();
        return saveBatch(deStudent);
    }

    @Override
    public boolean saveOrUpdateScore(Integer studentId, Integer score)throws RuntimeException {
        //先判断是否存在；不存在则添加
        LambdaQueryWrapper<DeScore> lambda = new QueryWrapper<DeScore>().lambda();
        lambda.eq(DeScore::getStudentid, studentId);
        DeScore deScore = deScoreMapper.selectOne(lambda);
        if (deScore==null) {
             //
            DeScore createInfo = deScoreMapper.getStudentByStudentId(studentId);
            if (createInfo==null) {
                throw new RuntimeException("在学部信息中找不到该学生的信息，操作失败");
            }
            createInfo.setScore(score);
            return save(createInfo);
        }
        deScore.setScore(deScore.getScore()+score);
        return updateById(deScore);
    }

    @Override
    public Result<Map<Integer, List<DeScore>>> getDeScore() {
        // 获取每个学部前五的；
        LambdaQueryWrapper<DeScore> lambda = new QueryWrapper<DeScore>().lambda();
        Map<Integer, List<DeScore>> collect = deScoreMapper.getDeStudentInfoDesc(5).stream().collect(Collectors.groupingBy(DeScore::getDeid));
        return Result.success(collect);
    }

    @Override
    public boolean updateScore() {
        return deScoreMapper.updateDeStudent()>0;
    }

    @Override
    public boolean delDeInfo() {
        return remove(null);
    }
}
